package main

import (
	"context"
	"fmt"
	"github.com/flipped-aurora/gin-vue-admin/server/model/Elasticsearchs"
	"github.com/olivere/elastic/v7"
	"github.com/robfig/cron/v3"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"strconv"
)

// MySQL数据同步Es
func SyncEs() {
	ctx := context.Background()
	client, _ := elastic.NewClient(elastic.SetURL("http://8.130.109.242:9200"), elastic.SetSniff(false))
	//查询数据库中的数据
	//连接数据库
	dsn := "root:root@tcp(127.0.0.1:3307)/interview_title?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	goodData := []Elasticsearchs.InterviewEsEdit{}
	db.Table("interview").Find(&goodData)

	//同步数据到es中
	for _, v := range goodData {
		idstr := strconv.Itoa(int(v.ID))
		_, err := client.Index().
			Index("interview").
			Type("_doc").
			Id(idstr).
			BodyJson(v).
			Do(ctx)
		if err != nil {
			// Handle error
			fmt.Println(err)
		}
	}
	fmt.Println("数据同步成功")
}

func main() {
	cr := cron.New()
	cr.AddFunc("30 09 * * *", SyncEs)
	cr.Start()
	select {}

}
